package me.fung.wubi.entry

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.ResourceLoader
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.*
import me.fung.keen.app.nav.HOME
import me.fung.keen.component.message.MessageContent
import me.fung.wubi.app.navigation
import me.fung.wubi.repo.*
import mu.KotlinLogging
import java.io.File
import java.sql.Connection
import me.fung.wubi.repo.configWindowPlacement as configWindowPlacement1

private val logger = KotlinLogging.logger { }

@OptIn(ExperimentalComposeUiApi::class)
fun application(args: Array<String>) {
    init(args)
    application {
        val ws = rememberWindowState(
            placement = WindowPlacement.entries[configWindowPlacement1],                        //WindowPlacement.Floating,
            position = WindowPosition(configWindowPositionX.dp, configWindowPositionY.dp),
            size = DpSize(configWindowSizeWidth.dp, configWindowSizeHeight.dp),
        )
        LaunchedEffect(ws.placement, ws.position, ws.size) {
            configWindowPlacement1 = ws.placement.ordinal
            if (ws.placement == WindowPlacement.Floating) {
                configWindowPositionX = ws.position.x.value
                configWindowPositionY = ws.position.y.value
                configWindowSizeWidth = ws.size.width.value
                configWindowSizeHeight = ws.size.height.value
            }
        }
        Window(
            onCloseRequest = ::exitApplication,
            title = "五笔工厂",
            state = ws,
        ) {
            LaunchedEffect(Unit) {
                navigation.goto(HOME)
            }
            Box(Modifier.fillMaxSize()) {
                navigation.show(Modifier.fillMaxSize())
                MessageContent().show(Modifier.fillMaxWidth().height(50.dp).align(Alignment.BottomCenter))
            }
        }
    }
}

fun init(args: Array<String>) {
    logger.info { "Start with args: ${args.joinToString(",")}" }

    val data = File(DATA)
    if (!data.exists()) {
        data.mkdirs()
    }

    val init = File(TAG)
    if (!init.exists()) {
        createDatabase()
        init.createNewFile()
    }


}

private fun Connection.sql(sql: String) {
    this.createStatement().execute(sql)
}